# -*- coding: utf-8 -*-
import urllib
import GetMysql
from geopy.distance import geodesic
from pandas._libs import json
import datetime
import countour_predict_value as cpv
from math import cos, sin, atan2, sqrt, radians, degrees

#基于百度地图API下的经纬度信息来解析地理位置信息
def get_location(lat,lng):
    #31.809928, 102.537467, 3019.300
    #lat = '31.809928'
    #lng = '102.537467'
    url = 'http://api.map.baidu.com/geocoder/v2/?location=' + lat + ',' + lng + '&output=json&pois=1&ak=003EurM0nat1YfowgMZPIBpDtGjbGOri'
    req = urllib.request.urlopen(url)  # json格式的返回数据
    res = req.read().decode("utf-8")  # 将其他编码的字符串解码成unicode
    return json.loads(res)

def jsonFormatAdd(lat,lng):
    addstr = get_location(lat,lng)
    dictjson={}#声明一个字典
    #get()获取json里面的数据
    jsonResult = addstr.get('result')
    address = jsonResult.get('addressComponent')
    #国家
    country = address.get('country')
    #国家编号（0：中国）
    # country_code = address.get('country_code')
    #省
    # province = address.get('province')
    #城市
    city = address.get('city')
    #城市等级
    # city_level = address.get('city_level')
    #县级
    district = address.get('district')
    # 乡镇名
    town = address.get('town')
    # 街道名street
    street = address.get('street')
    # 街道门牌号
    street_number = address.get('street_number')
    #把获取到的值，添加到字典里（添加）
    dictjson['country']=country

    dictjson['city'] = city

    dictjson['district']=district
    dictjson['town']=town
    dictjson['street']=street
    dictjson['street_number']=street_number


    return dictjson.values()

def error_range(lat,lng,result_lat,result_lng):
    distance_fm = geodesic((lat,lng), (result_lat,result_lng)).m
    return distance_fm

def get_device_addr(frequency,deviceidlist):
    datadict = {}
    result = []
    print('在get_device_addr 打印数据——————————————————————————————————————————————————-')
    print(frequency)
    
    for deviceid in deviceidlist:
        print(deviceid)
        result_rssi = GetMysql.get_device_rssi(deviceid,frequency)
        for i in result_rssi:
            datadict[i[0]]=i[1]
    for key,value in datadict.items():
        if(value == max(datadict.values())):
            result_add = GetMysql.get_device_address(key)
            lon = result_add['lon']
            lat = result_add['lat']
            result.append(frequency)
            result.append(lon)
            result.append(lat)
            result.append(deviceidlist)
            result.append(6)
            return result 


def location_computed(frequency,span,device):
    endtime = str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    starttime = str((datetime.datetime.now()+datetime.timedelta(hours= span)).strftime('%Y-%m-%d %H:%M:%S'))
    res =GetMysql.get_deviceids(frequency)
    # res = [['123456780001734', '123456780001635'],['123456780002665', '123456780001733']]
    # print('打印res的值',res)
    pointlist = []
    datalist = []
    resultlist = []      
    for devicelist in res: 
        # print('打印num的值',num)
        # str_devicelist = ','.join(device)
        result = cpv.pred_location( frequency ,endtime,starttime,device )
        if result is not None :
            resultlist.append(result)
        else:
            for i in devicelist:
                # print('打印i的值',i)
                result_point = GetMysql.get_point(i)
                pointlist.append(result_point)
                # print(result_point)

            res_point = center_geolocation(pointlist)
            # print('打印res_point的值',res_point)
            # datalist.append(frequency)
            # datalist.append(res_point[0])
            # datalist.append(res_point[1])
            # datalist.append(i)
            # datalist.append(6)
            datalist = [frequency,res_point[0],res_point[1],i,6]
            # print('-----------------',datalist)
            resultlist.append(datalist)
            # print('++++++++++++++++++++=',resultlist)
    return resultlist

def center_geolocation( geolocations):
        """
        输入多个经纬度坐标，找出中心点
        :param geolocations: 集合
        :return: 
        """
        x = 0
        y = 0
        z = 0
        length = len(geolocations)
        # print('打印传过来的geolocations的值',geolocations)
        for i in geolocations:
            lon = radians(float(i['lon']))
            lat = radians(float(i['lat']))
            x += cos(lat) * cos(lon)
            y += cos(lat) * sin(lon)
            z += sin(lat)

        x = float(x / length)
        y = float(y / length)
        z = float(z / length)

        return (degrees(atan2(y, x)), degrees(atan2(z, sqrt(x * x + y * y))))